using Headsight.BPMN2WF.BPMN.Model;
using System.Xml;

namespace Headsight.BPMN2WF.Transformation.BPMN2TransformerMappings.Config
{
    /// <summary>
    /// <see cref="IBPMN2WFTransformations"/> default implementation.
    /// </summary>
    public class BPMN2WFTransformationConfig : IBPMN2WFTransformations
    {
        private readonly BPMN2WFTransformationConfigMaps _configurationMaps;

        private BPMN2WFTransformationConfig()
        {
        }

        public BPMN2WFTransformationConfig(string mappingConfigFilename)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(mappingConfigFilename);
            _configurationMaps = BPMN2WFTransformationConfigMaps.ReadConfigFromXml(xmlDoc);
        }

        public BPMN2WFTransformationConfig(XmlDocument mappingConfig)
        {
            _configurationMaps = BPMN2WFTransformationConfigMaps.ReadConfigFromXml(mappingConfig);
        }

        public IBPMN2WFTransformation Get(BPMNFlowNode flowNode)
        {
            var actualFlowNode = (flowNode is BPMNFlowNodesBlock)
                                     ? ((BPMNFlowNodesBlock) flowNode).FlowNodeIn
                                     : flowNode;

            var typeOfFlowElement = actualFlowNode.TElement.GetType();

            foreach (var map in _configurationMaps.ConfigMaps)
            {
                if (map.Matches(flowNode, typeOfFlowElement))
                    return map.DestinationObject;
            }

            return _configurationMaps.DefaultDestinationObject;
        }
    }
}